package thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created with IntelliJ IDEA.
 * ClassName: Demo1
 * Package: thread
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-10-10
 * Time: 10:26
 */

//创建一个类 实现Callable的实现类
class Num implements Callable{

    //重写call方法
    @Override
    public Object call() throws Exception {
        //线程执行逻辑
        int a = 0;
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0){
                a += i;
            }
        }
        return a;
    }
}

//Callable接口创建线程
public class Demo1 {
    public static void main(String[] args) {
        //创建Callable接口实现类对象
        Num num = new Num();
        //将实例传给FutureTask构造器中
        FutureTask futureTask = new FutureTask(num);
        //在将future实例传给Thread
        Thread t = new Thread(futureTask);
        t.start();
        //接收返回值
        try {
            Object o = futureTask.get();
            System.out.println("返回值总和: " + o);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
